package com.example.badminton.controller;

import com.example.badminton.common.Result;
import com.example.badminton.common.AnonymousAccess;
import com.example.badminton.entity.Review;
import com.example.badminton.service.ReviewService;
import com.example.badminton.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/review")
@CrossOrigin
public class ReviewController {

    @Autowired
    private ReviewService reviewService;

    @PostMapping("/create")
    public Result<Review> createReview(@RequestBody Review review) {
        Long userId = UserUtils.getCurrentUserId();
        review.setUserId(userId);
        reviewService.save(review);
        return Result.success(review);
    }

    @GetMapping("/list")
    public Result<List<Review>> getReviewList() {
        List<Review> reviews = reviewService.list();
        return Result.success(reviews);
    }

    @GetMapping("/court/{courtId}")
    public Result<List<Review>> getReviewsByCourtId(@PathVariable Long courtId) {
        List<Review> reviews = reviewService.getReviewsByCourtId(courtId);
        return Result.success(reviews);
    }

    @GetMapping("/{id}")
    public Result<Review> getReviewById(@PathVariable Long id) {
        Review review = reviewService.getById(id);
        if (review == null) {
            return Result.error("评价不存在");
        }
        return Result.success(review);
    }

    @PutMapping("/{id}")
    public Result<Review> updateReview(@PathVariable Long id, @RequestBody Review review) {
        Long userId = UserUtils.getCurrentUserId();
        
        Review existingReview = reviewService.getById(id);
        if (existingReview == null) {
            return Result.error("评价不存在");
        }
        
        // 检查权限：只能修改自己的评价
        if (!existingReview.getUserId().equals(userId) && !UserUtils.isAdmin()) {
            return Result.error("无权限修改此评价");
        }
        
        review.setId(id);
        review.setUserId(userId);
        reviewService.updateById(review);
        return Result.success(review);
    }

    @DeleteMapping("/{id}")
    public Result<String> deleteReview(@PathVariable Long id) {
        Long userId = UserUtils.getCurrentUserId();

        Review review = reviewService.getById(id);
        if (review == null) {
            return Result.error("评价不存在");
        }
        
        // 检查权限：只能删除自己的评价
        if (!review.getUserId().equals(userId) && !UserUtils.isAdmin()) {
            return Result.error("无权限删除此评价");
        }
        
        reviewService.removeById(id);
        return Result.success("删除成功");
    }

    @GetMapping("/user")
    public Result<List<Review>> getUserReviews() {
        Long userId = UserUtils.getCurrentUserId();

        List<Review> reviews = reviewService.getReviewsByUserId(userId);
        return Result.success(reviews);
    }
} 